import fetch from 'cross-fetch'
import Cookie from 'js-cookie'
import * as types from '../constants/ActionTypes'
import { requestBaseUrl } from '../constants/AjaxConfig'
// synchronous action creators
export const addTodo = text => ({ type: types.ADD_TODO, text })
export const deleteTodo = id => ({ type: types.DELETE_TODO, id })
export const editTodo = (id, text) => ({ type: types.EDIT_TODO, id, text })
export const completeTodo = id => ({ type: types.COMPLETE_TODO, id })
export const completeAllTodos = () => ({ type: types.COMPLETE_ALL_TODOS })
export const clearCompleted = () => ({ type: types.CLEAR_COMPLETED })

// asynchronous action creators
export const requestLogin = () => ({type: types.REQUEST_LOGIN})
export const receiveLogin = (username, error) => (
    {type: types.RECEIVE_LOGIN, username, error}
)
export const fetchTodolist = (data, error) => ({type: types.FETCH_TODOLIST, data, error})
export const postTodolist = (msg) => ({type: types.POST_TODOLIST, msg})

export const logout = (error) => ({type: types.LOGOUT, error})
export const profileUpdated = (newProfile, error) => ({type: types.NEWPROFILE, error, newProfile})

const LOGIN_URL = requestBaseUrl + 'rest-auth/login/'
const processResponse = response => {
    if(response.ok)
        return null
    else{
        return response.json()
    }
}
export const makeLogin = (username, password) => {
    return function(dispatch) {
        dispatch(requestLogin())
        let submitStr = JSON.stringify({username, password});
        let loginConfig =  {
            body: submitStr,
            headers: {
                "Content-Type": "application/json",
            },
            method: 'POST',
            credentials: 'include'
        }
        return fetch(LOGIN_URL, loginConfig)
            .then(processResponse)
            .then((error) => dispatch(receiveLogin(username, error)),
            error => dispatch(receiveLogin('', error.toString())))
    }
}
const LOGOUT_URL = requestBaseUrl + 'rest-auth/logout/'
export const makeLogout = () => {
    const CSRFToken = Cookie.get('csrftoken')    
    const logoutConfig = {
        credentials: 'include', 
        method: 'POST',
        headers: {
            'X-CSRFToken': CSRFToken
        },        
    }
    return function(dispatch) {
        return fetch(LOGOUT_URL, logoutConfig)
                .then(processResponse)
                .then(error => dispatch(logout(error)),
                 error => dispatch(logout(error.toString())))
    }    
}
const TODO_URL = requestBaseUrl + 'todolist/file'
export const makeFetchTodo = () => {
    return function(dispatch) {
        return fetch(TODO_URL, {credentials: 'include'})
            .then(response => response.json())
            .then(json => {
                if(json.code < 0)
                    dispatch(fetchTodolist(null, json.msg))
                else{
                    let todos = JSON.parse(json.data)
                    dispatch(fetchTodolist(todos, null))
                }
            }, error => dispatch(fetchTodolist(null, error.toString())))
    }
}
export const makePostTodo = () => {
    return function(dispatch, getState) {
        let todos = getState().todos
        let submitStr = JSON.stringify(todos)
        let PostTodoConfig = {
            body: submitStr,
            method: 'POST',
            credentials: 'include'            
        }
        return fetch(TODO_URL, PostTodoConfig)
            .then(response => response.json())
            .catch(error => dispatch(postTodolist(error)))
            .then(json => {
                if(json.code < 0)
                    dispatch(postTodolist(json.msg))
                else
                    dispatch(postTodolist(null))
            })
    }
}
const updateProfileUrl = requestBaseUrl + 'rest-auth/user/' 
export const updateProfile = (submitedProfile) => {
    return function(dispatch) {
        let updateConfig =  {
            body: submitedProfile,
            headers: {
                "Content-Type": "application/json",
                'X-CSRFToken': Cookie.get('csrftoken')
            },
            method: 'PATCH',
            credentials: 'include'
        }
        return fetch(updateProfileUrl, updateConfig)
            .then(processResponse)
            .then((error) => dispatch(profileUpdated(submitedProfile, error)),
            error => dispatch(profileUpdated({}, error.toString())))
    }
}